package org.dtrd.modules.message.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.common.PathUtil;
import org.dtrd.config.pay.OrderUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.Constant.USER_CATEGORY;
import org.dtrd.config.wechat.api.impl.WechatApi;
import org.dtrd.config.wechat.config.WechatUtil;
import org.dtrd.config.wechat.config.officialaccount.WechatTemplateConfig.TemplatePlan;
import org.dtrd.config.wechat.entity.bean.officialaccount.WechatTemplateParams;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.*;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.ServiceStateMsg.ServiceStateMsgBuilder;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.SigninSuccessMsg.SigninSuccessMsgBuilder;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.SigninMissMsg.SigninMissMsgBuilder;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.SuggestMsg.SuggestMsgBuilder;
import org.dtrd.modules.doctor.entity.po.DtrdEntRdDoctor;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.record.entity.bean.AbnormalSugarRecordBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author xiao
 * @date 2022/6/1 10:25 AM
 */
@Component
@Slf4j
public class MsgEventPusher {

    @Autowired
    private IDtrdEntRdPatientService patientService;

    @Autowired
    private IDtrdEntRdDoctorService doctorService;

    @Autowired
    private IDtrdRlDoctorPatientService doctorPatientService;

    @Autowired
    private WechatApi wechatApi;

    /**
     * 发送服务项目完成事件
     *
     * @param patientId
     * @param serviceName
     * @param packageId
     * @param isFinish
     */
    public void sendServiceItemStateChangeEvent(Integer patientId, String serviceName, Integer packageId, boolean isFinish) {
        DtrdEntRdPatient patient = patientService.getById(patientId);
        if (patient == null) {
            return;
        }
        if (patient.getDoctorId() != null) {
            // 发送给医生 患者关联的医生非空
            DtrdEntRdDoctor doctor = doctorService.getById(patient.getDoctorId());
            if (doctor.getWxOaOpenid() != null) {
                String patientName = StrUtil.isBlank(patient.getPatientsName()) ? patient.getPatientsMobile() : patient.getPatientsName();
                ServiceStateMsg msg;
                if (isFinish) {
                    msg = ServiceStateMsg.ServiceStateMsgBuilder.singleInstance()
                            .buildServiceItemStateChangeForDoctor(patientName, serviceName, patientId, doctor.getDataId(), packageId)
                            .build();
                } else {
                    msg = ServiceStateMsg.ServiceStateMsgBuilder.singleInstance()
                            .buildServiceItemStateChangeForDoctor(patientName, serviceName, patient.getDataId(), doctor.getDataId(), packageId)
                            .build();
                }
                wechatApi.sendTemplateService(msg, doctor.getWxOaOpenid());
            }
        }
        // 发送给患者
        if (patient.getWxOaOpenid() != null) {
            ServiceStateMsg msg;
            if (isFinish) {
                msg = ServiceStateMsg.ServiceStateMsgBuilder.singleInstance()
                        .buildServiceItemStateChangeForPatient(serviceName, patientId, packageId)
                        .build();
            } else {
                msg = ServiceStateMsg.ServiceStateMsgBuilder.singleInstance()
                        .buildServiceItemStateChangeForPatient(serviceName, patientId, packageId)
                        .build();
            }
            wechatApi.sendTemplateService(msg, patient.getWxOaOpenid());
        }
    }

    /**
     * 您已完成基本信息填写
     * 服务类型：基本信息
     * 服务状态：成功
     * 服务时间：2022-05-21 11:20
     * 点击立即联系您的医生
     */
    public void sendPatientBasicInfoEvent(Integer patientId, String openId, Integer doctorId) {
        if (StrUtil.isNotBlank(openId)) {
            // 基本消息填写完成
            String chatroomId = doctorPatientService.getChatroomIdByPatientId(patientId, doctorId);
            ServiceStateMsg msg = ServiceStateMsgBuilder.singleInstance()
                    .buildPatientBasicInfoMsg("基本信息", PathUtil.getChatroomUrl(USER_CATEGORY.USER_DOCTOR.getUser(), patientId + "", chatroomId), "点击立即联系您的医生")
                    .build();
            wechatApi.appointmentSucceed(msg, openId);
        }

    }

    /**
     * 发送支付完成消息
     * <p>
     * 患者支付成功：您的患者曾兰芳成功支付299元
     * 订单标题：XX血糖仪/试纸XX套/以旧换新
     * 订单金额：299元
     * 支付时间：2020-04-20 10:00
     * 点击向患者发送消息
     * </p>
     *
     * @param userId       患者ID
     * @param orderDataId  订单ID
     * @param orderInfoSum 订单金额
     * @param infoTitle    订单标题
     * @param orderNo      订单编号
     * @param payDateTime  支付时间
     */
    public void sendOrderPaySuccessMsg(int userId, String orderDataId, Long orderInfoSum, String infoTitle, String orderNo, Date payDateTime) {
        try {
            DtrdEntRdPatient patient = patientService.getById(userId);
            if (patient == null) {
                return;
            }
            String chatroomId = doctorPatientService.getChatroomIdByPatientId(userId, patient.getDoctorId());
            String payTime = DateUtils.formatTime(payDateTime);
            String paySum = OrderUtil.changeF2Y(orderInfoSum) + "元";
            if (patient.getDoctorId() != null) {
                // 发送给医生 患者关联的医生非空
                DtrdEntRdDoctor doctor = doctorService.getById(patient.getDoctorId());
                if (doctor.getWxOaOpenid() != null) {
                    String patientName = StrUtil.isBlank(patient.getPatientsName()) ? patient.getPatientsMobile() : patient.getPatientsName();
                    OrderStateMsg msg = OrderStateMsg.OrderStateMsgBuilder.getInstance()
                            .buildOrderPsySuccessMsg("您的患者" + patientName + "成功支付" + paySum,
                                    infoTitle,
                                    orderNo,
                                    paySum,
                                    payTime, PathUtil.getChatroomUrl(USER_CATEGORY.USER_DOCTOR.getUser(), patient.getDoctorId() + "", chatroomId),
                                    "点击向患者发送消息").build();
                    wechatApi.sendOrderPaySuccessMsg(msg, doctor.getWxOaOpenid());
                }
            }
            // 发送给患者
            if (patient.getWxOaOpenid() != null) {
                OrderStateMsg msg = OrderStateMsg.OrderStateMsgBuilder.getInstance()
                        .buildOrderPsySuccessMsg("您已成功支付" + paySum,
                                infoTitle,
                                orderNo,
                                paySum, payTime,
                                PathUtil.getChatroomUrl(USER_CATEGORY.USER_PATIENT.getUser(), userId + "", chatroomId), "点击立即联系医生")
                        .build();
                wechatApi.sendOrderPaySuccessMsg(msg, patient.getWxOaOpenid());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增建议
     * <p>
     * {{first.DATA}}
     * 意见内容：{{keyword1.DATA}}
     * 时间：{{keyword2.DATA}}
     * {{remark.DATA}}
     * 医生为您的饮食提出了建议，请及时查看！
     * 意见内容：【取建议内容】
     * 时间：2014年7月31日
     * 点击查看详情
     */
    public void addSuggest(@Nonnull String suggestContent, @Nonnull Integer patientId) {
        String openId = Optional.ofNullable(patientId).map(id -> patientService.getById(id)).map(DtrdEntRdPatient::getWxOaOpenid).orElse(null);
        if (openId != null) {
            SuggestMsg msg = SuggestMsgBuilder.singleInstance().buildDoctorDietSuggest(suggestContent, patientId);
            wechatApi.addSuggest(msg, openId);
        }
    }

    /**
     * 打卡成功
     * @param signinName
     * @param signinTime yyyy-MM-dd HH:mm:ss
     * @param patientId
     */
    public void signinSuccess(String signinName, String signinTime, Integer patientId) {
        String openId = Optional.ofNullable(patientId).map(id -> patientService.getById(id)).map(DtrdEntRdPatient::getWxOaOpenid).orElse(null);
        log.info("MsgEventPusher.signinSuccess.[signinName={}, signinTime={}, patientId={}", signinName, signinTime, patientId);
        if (openId != null) {
            DtrdEntRdPatient patient = patientService.getById(patientId);
            if (patient == null) {
                return;
            }
            // 给医生发送打卡成功消息
            if (patient.getDoctorId() != null) {
                DtrdEntRdDoctor doctor = doctorService.getById(patient.getDoctorId());
                if (doctor.getWxOaOpenid() != null) {
                    if (signinTime == null || signinTime.isEmpty()) {
                        signinTime = DateUtils.now();
                    }
                    String patientName = StrUtil.isBlank(patient.getPatientsName()) ? patient.getPatientsMobile() : patient.getPatientsName();
                    SigninMissMsg msg = SigninMissMsg.SigninMissMsgBuilder.singleInstance()
                            .buildSigninSuccessMsg(patientName, signinTime, patientId);
                    wechatApi.signinSuccessForDoctor(msg, doctor.getWxOaOpenid());
                }
            }
            // 给患者的打卡成功提醒暂时先不用
//            if (patient.getWxOaOpenid() != null) {
//                SigninSuccessMsg msg = SigninSuccessMsgBuilder.singleInstance().buildSigninSuccessMsg(signinName, signinTime, patientId);
//                wechatApi.signinSuccess(msg, openId);
//            }
        }
    }

    /**
     * 漏打卡
     *
     * @param patientId
     * @param signinName
     */
    public void signinMiss(int patientId, String signinName) {
        try {
            DtrdEntRdPatient patient = patientService.getById(patientId);
            if (patient == null) {
                return;
            }
            String patientName = StrUtil.isBlank(patient.getPatientsName()) ? patient.getPatientsMobile() : patient.getPatientsName();
            String chartroomId = doctorPatientService.getChatroomIdByPatientId(patientId, patient.getDoctorId());
            // 发送给医生漏打卡消息
            if (patient.getDoctorId() != null) {
                List<Integer> doctorIds = doctorService.getDoctorTeamMemberByPatientId(patient.getDataId());
                if (CollectionUtil.isNotEmpty(doctorIds)) {
                    doctorIds.forEach(doctorId -> {
                        DtrdEntRdDoctor doctor = doctorService.getById(doctorId);
                        if (doctor.getWxOaOpenid() != null) {
                            SigninMissMsg msg = SigninMissMsg.SigninMissMsgBuilder.singleInstance()
                                    .buildSigninMissMsg("患者未按时完成打卡，请及时关注患者情况并在后台完成补卡",
                                            patientName, signinName, "点击与患者联系",
                                            PathUtil.getChatroomUrl(USER_CATEGORY.USER_DOCTOR.getUser(), doctor.getDataId() + "", chartroomId), USER_CATEGORY.USER_DOCTOR.getUser()).build();
                            wechatApi.signinMiss(msg, doctor.getWxOaOpenid());
                        }
                    });
                }
                // DtrdEntRdDoctor doctor = doctorService.getById(patient.getDoctorId());
                // if (doctor.getWxOaOpenid() != null) {
                //     SigninMissMsg msg = SigninMissMsg.SigninMissMsgBuilder.singleInstance()
                //             .buildSigninMissMsg("患者未按时完成打卡，请及时关注患者情况并在后台完成补卡",
                //                     patientName, signinName, "点击与患者联系",
                //                     PathUtil.getChatroomUrl(USER_CATEGORY.USER_DOCTOR.getUser(), patient.getDoctorId() + "", chartroomId), USER_CATEGORY.USER_DOCTOR.getUser()).build();
                //     wechatApi.signinMiss(msg, doctor.getWxOaOpenid());
                // }
            }
            // 发送给患者漏打卡消息
            if (patient.getWxOaOpenid() != null) {
                SigninMissMsg msg = SigninMissMsg.SigninMissMsgBuilder.singleInstance()
                        .buildSigninMissMsg("患者您好，医生没有收到您的打卡数据，无法了解你近期的控制情况，请及时联系医师团队进行补卡哦",
                                patientName, signinName, "点击联系您的医师团队",
                                PathUtil.getChatroomUrl(USER_CATEGORY.USER_PATIENT.getUser(), patientId + "", chartroomId), USER_CATEGORY.USER_PATIENT.getUser()).build();
                wechatApi.signinMiss(msg, patient.getWxOaOpenid());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 血糖异常提醒（患者端）
     * abnormalSugarRecordBean
     */
    public void sugarValueAbnormal(AbnormalSugarRecordBean abnormalSugarRecordBean) {
        String openId = Optional.ofNullable(abnormalSugarRecordBean.getPatientId()).map(id -> patientService.getById(id)).map(DtrdEntRdPatient::getWxOaOpenid).orElse(null);
        Integer doctorId = Optional.ofNullable(abnormalSugarRecordBean.getPatientId()).map(id -> patientService.getById(id)).map(DtrdEntRdPatient::getDoctorId).orElse(null);
        // openId = "ok2z06CL1qBjcvfHqMID3s2z1mZ4";
        if (openId != null && doctorId != null) {
            String chatroomIdByPatientId = doctorPatientService.getChatroomIdByPatientId(abnormalSugarRecordBean.getPatientId(), doctorId);
            String url = PathUtil.getChatroomUrl(Constant.USER_CATEGORY.USER_PATIENT.getUser(), "" + abnormalSugarRecordBean.getPatientId(), chatroomIdByPatientId);
            AbnormalSugarMsg msg = AbnormalSugarMsg.AbnormalSugarMsgBuilder.singleInstance().buildAbnormalSugarMsg("您本次血糖打卡情况如下，如有身体不适请及时联系您的医疗团队！",abnormalSugarRecordBean.getTimeType(), abnormalSugarRecordBean.getSigninTime(), abnormalSugarRecordBean.getPatientId(), abnormalSugarRecordBean.getSugarValue(), abnormalSugarRecordBean.getWaveValue(), abnormalSugarRecordBean.getMessage(), url,"点击联系您的医师团队");
            log.info("buildAbnormalSugarMsg=" + abnormalSugarRecordBean + "== url = " + url);
            wechatApi.abnormalSugarValue(msg, openId);
        }
    }

    /**
     * 血糖提醒（医生端）
     */
    public void sugarValueAbnormalForDoctor(AbnormalSugarRecordBean abnormalSugarRecordBean) {
        DtrdEntRdPatient patient = patientService.getById(abnormalSugarRecordBean.getPatientId());
        if (patient == null) {
            return;
        }
        // Integer doctorId = patient.getDoctorId();
        List<Integer> doctorIds = doctorService.getDoctorTeamMemberByPatientId(patient.getDataId());
        String url = PathUtil.getH5Domain() + "/patient/?patientId=" + abnormalSugarRecordBean.getPatientId();
        if (CollectionUtil.isNotEmpty(doctorIds) && !abnormalSugarRecordBean.getMessage().equals("正常")) {
            doctorIds.forEach(doctorId -> {
                DtrdEntRdDoctor doctor = doctorService.getById(doctorId);
                if (doctor.getWxOaOpenid() != null) {
                    AbnormalSugarMsg msg = AbnormalSugarMsg.AbnormalSugarMsgBuilder.singleInstance().buildAbnormalSugarMsg("患者完成血糖打卡，如有异常情况请及时关注",abnormalSugarRecordBean.getTimeType(), abnormalSugarRecordBean.getSigninTime(), abnormalSugarRecordBean.getPatientId(), abnormalSugarRecordBean.getSugarValue(), abnormalSugarRecordBean.getWaveValue(), abnormalSugarRecordBean.getMessage(), url,"点击查看患者详情");
                    log.info("buildAbnormalSugarMsg=" + abnormalSugarRecordBean + "== url = " + url);
                    wechatApi.abnormalSugarValue(msg, doctor.getWxOaOpenid());
                }
            });
        }
        // if (doctorId != null) {
        //     DtrdEntRdDoctor doctor = doctorService.getById(doctorId);
        //     if (doctor.getWxOaOpenid() != null) {
        //         AbnormalSugarMsg msg = AbnormalSugarMsg.AbnormalSugarMsgBuilder.singleInstance().buildAbnormalSugarMsg("患者完成血糖打卡，如有异常情况请及时关注",abnormalSugarRecordBean.getTimeType(), abnormalSugarRecordBean.getSigninTime(), abnormalSugarRecordBean.getPatientId(), abnormalSugarRecordBean.getSugarValue(), abnormalSugarRecordBean.getWaveValue(), abnormalSugarRecordBean.getMessage(), url,"点击查看患者详情");
        //         log.info("buildAbnormalSugarMsg=" + abnormalSugarRecordBean + "== url = " + url);
        //         wechatApi.abnormalSugarValue(msg, doctor.getWxOaOpenid());
        //     }
        // }
    }
}
